<!-- // 完整的dome -->
<template>
	<div class="meClocker">
		<i class="iconfont icon-jishi"></i>
		<div class="txt-time">{{ msg }}</div>
		<div class="run-time" v-if="timeobj.hours || timeobj.minutes || timeobj.seconds">
			<span class="timing" v-if="timeobj.days">{{ timeobj.days + '天' }}</span>
			<span class="timing">{{ timeobj.hours | add0 }}</span>
			<span class="flag-time">:</span>
			<span class="timing">{{ timeobj.minutes | add0 }}</span>
			<span class="flag-time">:</span>
			<span class="timing">{{ timeobj.seconds | add0 }}</span>
		</div>
	</div>
</template>
<script>
export default {
	name: 'clock',
	data() {
		return {
			clocker: '', //显示倒计时
			timeobj: {
				days: 0,
				hours: 0,
				minutes: 0,
				seconds: 0
			},
			msg: '',
			setTiming: 0, //存放时间
			endTimeOver: this.endTime
		};
	},
	filters: {
		add0: function(num) {
			return num < 10 ? '0' + num : num;
		}
	},
	//timing 时长  isCountdown true是倒计时
	props: ['startTime', 'endTime', 'timing', 'isCountdown'],
	methods: {
		timeStatus() {
			this.setTiming = this.timing;
			clearInterval(this.go);
			let timeFunction = () => {
				if (!this.isCountdown) {
					this.setTiming++;
					this.msg = '计时';
				} else {
					if (this.timing <= 0) {
						this.stop();
					}
					this.setTiming--;
					this.msg = '倒计时';
					if (this.setTiming == 0) {
						this.end();
					}
				}
				this.timeobj = {
					days: Math.floor(this.setTiming / 60 / 60 / 24),
					hours: Math.floor((this.setTiming / 60 / 60) % 24),
					minutes: Math.floor((this.setTiming / 60) % 60),
					seconds: Math.floor(this.setTiming % 60)
				};
			};
			timeFunction();
			this.go = setInterval(() => {
				let curTime = this.timestampToTime(new Date().getTime());
				// this.endTimeOver = '2021/06/24 11:13';
				// console.log(this.endTimeOver < curTime, curTime, '结束时间');
				if (this.endTimeOver == curTime || this.endTimeOver < curTime) {
					// 如果超过了老师设定结束时间
					this.$emit('end', {});
				}
				timeFunction();
			}, 1000);
		},
		//时间戳转换
		timestampToTime(timestamp) {
			const dateObj = new Date(+timestamp); // ps, 必须是数字类型，不能是字符串, +运算符把字符串转化为数字，更兼容
			const year = dateObj.getFullYear(); // 获取年，
			const month = this.pad(dateObj.getMonth() + 1); // 获取月，必须要加1，因为月份是从0开始计算的
			const date = this.pad(dateObj.getDate()); // 获取日，记得区分getDay()方法是获取星期几的。
			const hours = this.pad(dateObj.getHours()); // 获取时, pad函数用来补0
			const minutes = this.pad(dateObj.getMinutes()); // 获取分
			return year + '/' + month + '/' + date + ' ' + hours + ':' + minutes;
		},
		pad(str) {
			return +str >= 10 ? str : '0' + str;
		},
		// 停止倒计时
		end() {
			// 清除定时器
			clearInterval(this.go);
			this.setTiming = null;
			this.$emit('end', {});
		},
		stop() {
			clearInterval(this.go);
			this.setTiming = null;
			this.$emit('timerSucess');
		}
	},
	created() {
		this.timeStatus();
	},
	destroyed() {
		clearInterval(this.go);
	}
};
</script>
<style scoped>
.meClocker {
	/* 	display flex;
	align-items center;
	justify-content center; */
}
</style>
